<template>
  <div class="commentSectionCont">
    <el-input
      v-if="!props.expandmode"
      v-model="commentInfo"
      type="textarea"
      placeholder="请输入评论"
      :maxlength="140"
      :show-word-limit="true"
      :rows="3"
      :resize="'none'"
      @keyup.delete="handleBack"
    />
    <div v-if="!props.expandmode" class="publishCommentRow">
      <div>表情/话题/@</div>
      <div>
        <div class="pulbishBtn" @click="handleAddComment">评论</div>
      </div>
    </div>
    <div class="newestComments" v-if="playlistCommentData?.hotComments">
      <div class="title">精彩评论</div>
      <div class="list">
        <CommentFloorVue
          v-for="comment in playlistCommentData.hotComments"
          :comment-data="comment"
          @onreply="readyToReply"
          @ondelete="deleteComment"
        />
      </div>
      <div class="moreHotCommentBtnCont">
        <div class="moreHotComments" @click="handleToAllHotComments">
          更多精彩评论>
        </div>
      </div>
    </div>
    <div class="newestComments">
      <div class="title">最新评论({{ playlistCommentData?.total }})</div>
      <div class="list">
        <CommentFloorVue
          v-for="comment in playlistCommentData?.comments"
          :comment-data="comment"
          @onreply="readyToReply"
          @ondelete="deleteComment"
        />
      </div>
      <div class="pagiCont">
        <el-pagination
          small
          layout="prev, pager, next"
          :total="playlistCommentData?.total"
          background
          :pageSize="fixedLimit"
          v-model:currentPage="newestCommentCurrent"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";

import { CommentType, Comment } from "@/types/comment";
import { usePlayListComment } from "@/hooks/commentHook";
import useCommentStore from "@/stores/comments";
import CommentFloorVue from "../CommentFloor/CommentFloor.vue";

const CommentStore = useCommentStore();

const fixedLimit = 50;

const props = defineProps<{
  playlistId?: number | string;
  albumnId?: number | string;
  songId?: number | string;
  sourceId?: number | string;
  commentSource: Number;
  expandmode?: boolean;
  onToHotComments?: () => void;
}>();

const emit = defineEmits(["commentSuccess"]);

const router = useRouter();
const newestCommentCurrent = ref(1);
const commentInfo = ref("");
const { playlistCommentData, queryPlaylistComment } = usePlayListComment(
  props.commentSource
);
const handleToAllHotComments = () => {
  let type;
  let id = props.sourceId;
  switch (props.commentSource) {
    case 3:
      type = 3;
      //"albumn";

      break;
    case 2:
      type = 2;
      //"playlist";

      break;
    case 0:
      type = 0;
    // "song";

    default:
      break;
  }
  if (id && type !== undefined) {
    typeof props.onToHotComments === "function" && props.onToHotComments();
    router.push({
      path: "hotComments",
      query: {
        id,
        type,
      },
    });
  }
};

const AfterCommentSuccess = (id: any, deleteFlag = false) => {
  emit("commentSuccess", deleteFlag);
  if (!deleteFlag) {
    commentInfo.value = "";
  }
  let timer: any = setTimeout(() => {
    if (id) {
      queryPlaylistComment({
        id,
        offset: (newestCommentCurrent.value - 1) * fixedLimit,
        limit: fixedLimit,
      });
    }
    clearTimeout(timer);
    timer = null;
  }, 300);
};

const handleAddComment = () => {
  if (commentInfo.value.trim() === "") {
    return;
  }

  try {
    let id: string | number | undefined = props.sourceId;
    // if (props.commentSource === CommentType["歌单"]) {
    //   id = props.playlistId;
    // }
    // if (props.commentSource === CommentType["歌曲"]) {
    //   id = props.songId;
    // }

    if (id !== undefined && !CommentStore.replyMode) {
      CommentStore.addComment({
        id,
        type: props.commentSource,
        content: commentInfo.value,
      }).then(() => {
        AfterCommentSuccess(id, false);
      });
    } else if (
      id !== undefined &&
      CommentStore.replyMode &&
      CommentStore.replyData
    ) {
      const nickName = CommentStore.replyData?.user.nickname;
      const rule = new RegExp("^回复" + nickName + "\:(.+)*", "i");

      let matchRes = rule.exec(commentInfo.value);

      if (matchRes) {
        const [full, replyContent] = matchRes;
        console.log(replyContent);
        if (replyContent) {
          CommentStore.setReplyContent(replyContent);
        }

        CommentStore.replyComment({
          id,
          type: props.commentSource,
          content: replyContent,
          commentId: CommentStore.replyData?.commentId,
        }).then(() => {
          AfterCommentSuccess(id, false);
        });
      }
    }
  } catch (err) {
    console.error(err);
  }
};
// todo 未登录时不给删除回复

const readyToReply = (data: Comment) => {
  CommentStore.setReplyData(data);
  CommentStore.setReplyMode(true);
  CommentStore.setReplyContent("");
  commentInfo.value = `回复${data.user.nickname}:`;
};

const deleteComment = (data: Comment) => {
  try {
    let id: string | number | undefined;
    // if (props.commentSource === CommentType["歌单"]) {
    //   id = props.playlistId;
    // }
    id = props.sourceId;
    if (id !== undefined) {
      CommentStore.deleteComment({
        id,
        type: props.commentSource,
        commentId: data.commentId,
      }).then(() => {
        AfterCommentSuccess(id, true);
      });
    }
  } catch (err) {
    console.error(err);
  }
};

const handleBack = (event) => {
  // 知识点https://www.javascriptc.com/vue3js/guide/events.html#%E4%BA%8B%E4%BB%B6%E4%BF%AE%E9%A5%B0%E7%AC%A6
  if (CommentStore.replyMode === true) {
    const nickName = CommentStore.replyData?.user.nickname;
    const rule = new RegExp("^回复" + nickName + "\:(.+)*", "i");

    let matchRes = rule.exec(commentInfo.value);

    if (matchRes === null) {
      // 退出回复模式力
      CommentStore.setReplyMode(false);
    } else {
      const [full, replyContent] = matchRes;
      console.log(replyContent);
      if (replyContent) {
        CommentStore.setReplyContent(replyContent);
      }
    }
  }
};

const query = (id?: string | number) => {
  // if (props.commentSource === CommentType["歌单"] && props.playlistId) {
  //   id = props.playlistId;
  // } else if (props.commentSource === CommentType["歌曲"] && props.songId) {
  //   id = props.songId;
  // }
  id = props.sourceId;
  if (id) {
    queryPlaylistComment({
      id,
      offset: (newestCommentCurrent.value - 1) * fixedLimit,
      limit: fixedLimit,
    });
  }
};

onMounted(() => {
  query();
});

watch(
  () => newestCommentCurrent.value,
  (newPage, oldPage) => {
    if (props.sourceId) {
      queryPlaylistComment(
        {
          id: props.sourceId,
          offset: (newPage - 1) * fixedLimit,
          limit: fixedLimit,
        },
        () => {
          newestCommentCurrent.value = newPage;
        }
      );
    }
  }
);
watch(
  () => props.sourceId,
  (n, o) => {
    query(n);
  }
);
</script>

<style lang="less">
.commentSectionCont {
  .publishCommentRow {
    color: #666;
    margin-top: 10px;
    height: 32px;
    display: flex;
    justify-content: space-between;
    .pulbishBtn {
      border: 1px solid #dbdbdb;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;

      width: 60px;
      cursor: pointer;
      &:hover {
        background-color: #f2f2f2;
      }
      border-radius: 16px;
    }
  }
  .newestComments {
    margin-top: 10px;
    .moreHotCommentBtnCont {
      display: flex;
      justify-content: center;
      margin: 20px 0;
      .moreHotComments {
        width: 128px;
        cursor: pointer;
        font-size: 14px;
        color: #444;
        &:hover {
          color: #666;
        }
        height: 30px;
        border-radius: 15px;
        border: 1px solid #ddd;
        text-align: center;
        line-height: 30px;
      }
    }
    .title {
      color: #333;
      font-weight: bold;
      font-size: 18px;
    }
    .pagiCont {
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .el-pagination.is-background .btn-next.is-active,
  .el-pagination.is-background .btn-prev.is-active,
  .el-pagination.is-background .el-pager li.is-active {
    background-color: var(--primary-color);
  }
}
</style>
